<template>
  <div class="p-4 bg-gray-50 min-h-screen">
    <div class="max-w-6xl mx-auto">
      <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">智慧食堂管理系统</h1>
        <div class="flex items-center space-x-2">
          <el-tag type="success">实时数据</el-tag>
          <span class="text-sm text-gray-500">{{ currentTime }}</span>
        </div>
      </div>

      <el-card shadow="hover" class="mb-6">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-4">
          <div>
            <h2 class="text-xl font-semibold text-gray-700">各时间段用餐人数统计</h2>
            <p class="text-gray-500 text-sm mt-1">展示食堂各时间段用餐人数分布情况</p>
          </div>
          <div class="flex items-center space-x-2 mt-2 md:mt-0">
            <el-button type="primary" size="small" @click="loadData">
              <i class="fas fa-sync-alt mr-1"></i> 刷新数据
            </el-button>
            <el-switch
              v-model="autoRefresh"
              active-text="自动刷新"
              inactive-text="手动刷新"
              size="small"
            />
            <el-tag v-if="autoRefresh" type="info" size="small">
              下次刷新: {{ nextRefreshTime }}
            </el-tag>
          </div>
        </div>

        <div id="line" class="w-full" style="height: 420px"></div>
      </el-card>

      <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <el-card shadow="hover">
          <div class="flex items-center">
            <div class="bg-blue-100 p-3 rounded-full mr-4">
              <i class="fas fa-users text-blue-500 text-xl"></i>
            </div>
            <div>
              <p class="text-gray-500 text-sm">当前用餐人数</p>
              <h3 class="text-2xl font-bold mt-1">{{ stats.currentUsers }}</h3>
            </div>
          </div>
        </el-card>

        <el-card shadow="hover">
          <div class="flex items-center">
            <div class="bg-green-100 p-3 rounded-full mr-4">
              <i class="fas fa-utensils text-green-500 text-xl"></i>
            </div>
            <div>
              <p class="text-gray-500 text-sm">今日累计用餐</p>
              <h3 class="text-2xl font-bold mt-1">{{ stats.todayTotal }}</h3>
            </div>
          </div>
        </el-card>

        <el-card shadow="hover">
          <div class="flex items-center">
            <div class="bg-purple-100 p-3 rounded-full mr-4">
              <i class="fas fa-clock text-purple-500 text-xl"></i>
            </div>
            <div>
              <p class="text-gray-500 text-sm">高峰时间段</p>
              <h3 class="text-2xl font-bold mt-1">{{ stats.peakTime }}</h3>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import request from '@/utils/request';

// 图表容器引用
const lineBox = ref(null);
// 自动刷新状态
const autoRefresh = ref(true);
// 当前时间
const currentTime = ref('');
// 下次刷新时间
const nextRefreshTime = ref('');
// 统计数据
const stats = ref({
  currentUsers: 142,
  todayTotal: 328,
  peakTime: '11:30-13:00'
});

// 图表配置
const option = {
  title: {
    text: '各时间段用餐人数分布',
    left: 'center',
    textStyle: {
      fontSize: 16,
      fontWeight: 'bold'
    }
  },
  tooltip: {
    trigger: 'axis',
    formatter: '{b}: {c} 人',
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderColor: '#ddd',
    borderWidth: 1,
    textStyle: {
      color: '#333'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ["0:00-8:00", "8:00-16:00", "16:00-24:00"],
    axisLine: {
      lineStyle: {
        color: '#ccc'
      }
    },
    axisLabel: {
      fontSize: 12
    }
  },
  yAxis: {
    type: 'value',
    name: '人数',
    nameTextStyle: {
      fontSize: 12
    },
    axisLine: {
      show: true,
      lineStyle: {
        color: '#ccc'
      }
    },
    splitLine: {
      lineStyle: {
        type: 'dashed',
        color: '#eee'
      }
    }
  },
  series: [
    {
      name: '用餐人数',
      type: 'line',
      smooth: true,
      data: [45, 218, 152],
      itemStyle: {
        color: '#36a2eb'
      },
      lineStyle: {
        width: 3,
        color: '#36a2eb'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(54, 162, 235, 0.5)' },
          { offset: 1, color: 'rgba(54, 162, 235, 0.1)' }
        ])
      },
      symbol: 'circle',
      symbolSize: 8
    }
  ]
};

// 加载数据
const loadData = async () => {
  try {
    // 模拟API请求
    const res = await request.get("/admin/mealtime");
    
    // 更新图表数据
    option.series[0].data = res.content || [45, 218, 152];
    
    if (lineBox.value) {
      lineBox.value.setOption(option);
    }
    
    // 更新统计信息
    updateStats();
    
    console.log('数据刷新成功');
  } catch (error) {
    console.error('数据加载失败:', error);
  }
};

// 更新统计数据
const updateStats = () => {
  // 模拟实时数据变化
  stats.value = {
    currentUsers: Math.floor(120 + Math.random() * 50),
    todayTotal: Math.floor(300 + Math.random() * 50),
    peakTime: '11:30-13:00'
  };
};

// 更新时间
const updateTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
  
  if (autoRefresh.value) {
    const next = new Date(now.getTime() + 10000);
    nextRefreshTime.value = next.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  }
};

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('line');
  if (chartDom) {
    lineBox.value = echarts.init(chartDom);
    lineBox.value.setOption(option);
    
    // 响应窗口大小变化
    window.addEventListener('resize', () => {
      lineBox.value.resize();
    });
  }
};

// 设置定时器
let refreshTimer = null;
let timeTimer = null;

onMounted(() => {
  initChart();
  loadData();
  
  // 更新时间
  updateTime();
  timeTimer = setInterval(updateTime, 1000);
  
  // 设置自动刷新
  refreshTimer = setInterval(() => {
    if (autoRefresh.value) {
      loadData();
    }
  }, 10000);
});

onBeforeUnmount(() => {
  if (refreshTimer) clearInterval(refreshTimer);
  if (timeTimer) clearInterval(timeTimer);
  if (lineBox.value) lineBox.value.dispose();
});
</script>

<style scoped>
.el-card {
  border-radius: 10px;
  border: none;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
}

#line {
  border-radius: 8px;
  background-color: #fff;
}
</style>